#include "tcp_client.h"
#include "utils.h"
#include <iostream>

namespace OHOS {
namespace DistributedHardware {
TcpClient::TcpClient()
{
    sock_ = INVALID_SOCKET;
}

TcpClient::~TcpClient()
{
    close(sock_);
}

int TcpClient::TcpConnectSocket(const char* ip, uint16_t port)
{
    if (sock_ != INVALID_SOCKET) {
        close(sock_);
    }
    sock_ = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_ == INVALID_SOCKET) {
        std::cout << "socket creat fail" << std::endl;
        return INVALID_SOCKET;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    if (inet_aton(ip, &(addr.sin_addr)) == -1) {
        return INVALID_SOCKET;
    }
    char ipAddress[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(addr.sin_addr), ipAddress, INET_ADDRSTRLEN);

    int ret = connect(sock_, (struct sockaddr*)&addr, sizeof(addr));
    if (ret == -1) {
        return INVALID_SOCKET;
    }
    return sock_;
}

void TcpClient::SetSession(int sock)
{
    sock_ = sock;
}

int TcpClient::RecvData(char* buff, size_t size)
{
    memset(buff, 0 , size);
    int ret = read(sock_, buff, size);
    if (ret <= 0) {
        return false;
    }
    return ret;
}

int TcpClient::SendData(char* buff, size_t size)
{
    int ret = write(sock_, buff, size);
    if (ret <= 0) {
        return false;
    }
    return ret;
}

void TcpClient::CloseSocket()
{
    close(sock_);
}
}
}
